<?php

namespace AppBundle\Controller;

use AppBundle\Entity\Products;
use AppBundle\Form\ProductsType;
use FOS\RestBundle\View\View;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;

/**
 * Class ProductsController
 * @package AppBundle\Controller
 */
class ProductsController extends BaseController
{
    /**
     * @Route("/product/lists")
     * @Method({"GET"})
     * @return View
     */
    public function getProductListsAction()
    {
        $productLists = $this->getDoctrine()->getRepository('AppBundle:Products')
                     ->findAll();

        $view = new View();
        $view->setData(array(
            'lists'=>$productLists
        ));

        return $view;
    }

    /**
     * @param Request $request
     *
     * @Route("/products/add")
     * @Method({"GET","POST"})
     * @return View
     */
    public function addProductsAction(Request $request)
    {
        $product = new Products();
        $form = $this->createForm(new ProductsType(),$product);
        $form->handleRequest($request);

        if( $form->isSubmitted() && $form->isValid() )
        {
            $em = $this->getDoctrine()->getManager();
            $em->persist($product);
            $em->flush();
        }

        //$view = new View();
//        $view = $this->view($form->createView(),200)
//            ->setTemplate('products/new.html.twig')
//            ->setTemplateVar('form');
//
//       return $this->handleView($view);

        return $this->render('products/new.html.twig',array(
            'form'=>$form->createView()
        ));
    }

    /**
     * @param Request $request
     *
     * @Route("/product")
     * @Method({"POST"})
     * @return View
     */
    public function postProductsAction(
        Request $request
    )
    {
        $product = new Products();
        $form = $this->createForm(new ProductsType(),$product);
        $form->handleRequest($request);

        if(!$form->isValid()){
            throw new BadRequestHttpException("Bad Parameters");
        }

        $em = $this->getDoctrine()->getManager();
        $em->persist($product);
        $em->flush();

        return new View($product->getId());
    }
}